package com.pe1n.yangtaopai.helper;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

/**
 * Created by My on 2016/12/1.
 */

public class OkHttpClientHelper {
    private static  OkHttpClient client;
     private static BasicParamsInterceptor basicParamsInterceptor;

    public static OkHttpClient getClient(){

        Cache cache=new Cache(new File(Environment.getExternalStorageDirectory(),"temp"),20*1024*1024);

        OkHttpClient.Builder b = new OkHttpClient.Builder();
        basicParamsInterceptor=new BasicParamsInterceptor.Builder()
                .addQueryParam("basicparama1","aaa")
                .addQueryParam("basicparama2","bbb")
                .addQueryParam("basicparama3","ccc")
                .addQueryParam("basicparama4","ddd")
                .addHeaderParam("Cache-Control","public,max-age=3600") //指定请求和响应遵循的缓存机制
                .addHeaderParam("Connection","Keep-Alive") //表示是否需要持久连接。
                .addHeaderParam("Accept-Encoding","gzip")//指定可以支持的web服务器返回内容压缩编码类型。
                .build();

        HttpLoggingInterceptor logging=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e("=============",message);
            }
        });

        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

       //  b. addInterceptor( basicParamsInterceptor)
            b.addNetworkInterceptor(logging)
                    .cache(cache)
                //本地缓存拦截器
                //如何服务器返回的数据中包含 Cache-Control,OkHttp自动缓存
                //如何不包含 Cache-Control， 需要手动加上 Cache-Control
                //实现 OkHttp自动缓存

        .addInterceptor(new RewriteCacheControlInterceptor())
                .addNetworkInterceptor(new RewriteCacheControlInterceptor());
         b.connectTimeout(20, TimeUnit.SECONDS)
         .readTimeout(20,TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS);
        client=b.build();
        return client;

    }
}
